package com.example.noobpackage.ui.util

import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavOptions
import androidx.navigation.fragment.findNavController
import com.example.noobpackage.R
import com.example.noobpackage.logic.model.ApplicationUser
import com.example.noobpackage.ui.MainViewModel
import com.example.noobpackage.ui.login.LoginFragment

open class LoginRequiredFragment : Fragment() {
    private val shareViewModel: MainViewModel by activityViewModels()

    // 设置登录成功的返回锚点
    fun setupReturn() {
        val navController = findNavController()

        // 获取登陆状态值
        val currentBackStackEntry = navController.currentBackStackEntry!!
        val savedStateHandle = currentBackStackEntry.savedStateHandle

        // 根据状态值进行跳转
        savedStateHandle.getLiveData<Boolean>(LoginFragment.LOGIN_SUCCESSFUL)
            .observe(currentBackStackEntry) { success ->
                // 如果未登陆成功 则返回最开始的页面
                if (!success) {
                    val startDestination = navController.graph.startDestination
                    // 将所有页面出栈
                    val navOptions = NavOptions.Builder()
                        .setPopUpTo(startDestination, true)
                        .build()
                    navController.navigate(startDestination, null, navOptions)
                }
            }
    }

    // 登录成功的话 会初始化对应的fragment
    fun loginJudge(
        initializer: (ApplicationUser) -> Unit
    ) {
        val navController = findNavController()

        // 判断是否需要登录
        shareViewModel.userInfo.observe(viewLifecycleOwner) {
            if (it == null) navController.navigate(R.id.loginFragment)
            else initializer(it)
        }
    }
}